/**
 * 
 */
package com.shiplanet.service.impl;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

import com.shiplanet.dao.BaseDAO;
import com.shiplanet.dao.UserDAO;
import com.shiplanet.entity.User;
import com.shiplanet.entity.Visitor;
import com.shiplanet.service.UserService;

/**
 * @author joesong
 *
 */
@Service("userService")
public class UserServiceImpl implements UserService {
	@Resource
	private BaseDAO<Visitor> baseDAO;

	@Resource
	private UserDAO userDAO;

	@Resource
	private MailSender mailSender;

	@Resource
	private SimpleMailMessage templateMessage;

	private Logger logger = Logger.getLogger("userService");

	private static Pattern emailPattern = Pattern
			.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");	
	
	@Override
	public Integer saveVisitor(Visitor visitor) {
		return (Integer) baseDAO.save(visitor);
	}

	@Override
	public List<User> findUsersByExample(User user) {
		return userDAO.findUsersByExample(user);
	}

	@Override
	public boolean emailToUsers(String sendFrom, List<User> userSet, String emailSubject, String emailTemplate) {
		try {
			for (User u : userSet) {
					SimpleMailMessage msg = new SimpleMailMessage(
							this.templateMessage);
					msg.setSubject(emailSubject);
					
					emailTemplate = emailTemplate.replaceAll("\\$name", u.getName());

					msg.setText(emailTemplate);
					msg.setTo(u.getEmail());

					mailSender.send(msg);
					logger.info("an email has been sent to " + u.getName());
			}

		} catch (Exception ex) {
			logger.error(ex.getMessage());
			return false;
		}
		return true;
	}
	
	@Override
	public void excludeUsers(List<User> userList, String exclusionEmailList) {
		Set<String> exclusionEmailSet = new HashSet<String>();

		if (exclusionEmailList != null) {
			Matcher matchr = emailPattern.matcher(exclusionEmailList);
			while (matchr.find()) {
				String email = matchr.group();
				exclusionEmailSet.add(email);
			}
		}		
		
		Iterator<User> it = userList.iterator();
		while(it.hasNext()) {
			User u = it.next();
			if (exclusionEmailSet.contains(u.getEmail())) {
				it.remove();
			}			
		}		
	}
	
	@Override
	public String generateSendToList(List<User> userList) {
		StringBuffer sbSendTo = new StringBuffer();
		for (User u : userList) {
			sbSendTo.append(u.getEmail() + ";");
		}
		return sbSendTo.toString();
	}
}
